package com.edu.boot.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.boot.common.api.CommonResult;
import com.edu.boot.config.UserContext;
import com.edu.boot.entity.NotesManage;
import com.edu.boot.entity.Vo.NotesAndRecVo;
import com.edu.boot.entity.WorkRecord;
import com.edu.boot.enums.OfferStatus;
import com.edu.boot.enums.UserTypeEnum;
import com.edu.boot.service.NotesManageService;
import com.edu.boot.service.RecruitmentService;
import com.edu.boot.service.UserService;
import com.edu.boot.service.WorkRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作日志
 */
@RestController
@RequestMapping("/workRecord")
public class WorkRecordController {
    
    @Autowired
    private WorkRecordService workRecordService;
    @Autowired
    NotesManageService notesManageService;
    
    @Autowired
    UserService userService;
    
    @Autowired
    RecruitmentService recruitmentService;
    // 新增
    @PostMapping("/add")
    public CommonResult add(@RequestBody WorkRecord workRecord) {
        workRecord.setUId(UserContext.getUserId());
        workRecord.setCreateTime(DateUtil.date());
        NotesManage notesManage = notesManageService.getById(workRecord.getNotesId());
        if (notesManage == null) return CommonResult.failed("选择相关职位不存在，请核实");
        workRecord.setRecruitId(notesManage.getRecId());
        workRecord.setQyId(notesManage.getQyId());
        boolean saved = workRecordService.save(workRecord);
        return saved ? CommonResult.success("新增成功") : CommonResult.failed("新增失败");
    }
    
    // 修改
    @PostMapping("/update")
    public CommonResult<?> update(@RequestBody WorkRecord workRecord) {
        NotesManage notesManage = notesManageService.getById(workRecord.getNotesId());
        if (notesManage == null) return CommonResult.failed("选择相关职位不存在，请核实");
        workRecord.setRecruitId(notesManage.getRecId());
        workRecord.setQyId(notesManage.getQyId());
        boolean updated = workRecordService.updateById(workRecord);
        return updated ? CommonResult.success("更新成功") : CommonResult.failed("更新失败");
    }
    
    // 删除
    @GetMapping("/delete/{id}")
    public CommonResult<?> delete(@PathVariable Integer id) {
        boolean deleted = workRecordService.removeById(id);
        return deleted ? CommonResult.success("删除成功") : CommonResult.failed("删除失败");
    }
    
    // 单个查询
    @GetMapping("/find/{id}")
    public CommonResult<WorkRecord> findById(@PathVariable Integer id) {
        WorkRecord record = workRecordService.getById(id);
        return CommonResult.success(record);
    }
    
    // 列表查询（不分页）
    @GetMapping("/list")
    public CommonResult<List<WorkRecord>> list() {
        List<WorkRecord> list = workRecordService.list();
        return CommonResult.success(list);
    }
    
    // 分页查询（可传过滤条件）
    @GetMapping("/page")
    public CommonResult<IPage<WorkRecord>> page(
            @RequestParam() Integer currentpage,
            @RequestParam() Integer pagesize,
            @RequestParam(required = false) String recordTitle) {
        Page<WorkRecord> page = new Page<>(currentpage, pagesize);
        LambdaQueryWrapper<WorkRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(WorkRecord::getCreateTime);
        if(!UserTypeEnum.admin.getCode().equals(UserContext.getPid())){
            wrapper.eq(WorkRecord::getUId, UserContext.getUserId());
        }
        if (StringUtils.isNotBlank(recordTitle)) wrapper.like(WorkRecord::getRecordTitle, recordTitle);
        // 分页查询
        IPage<WorkRecord> result = workRecordService.page(page, wrapper);
        if(CollectionUtil.isNotEmpty(result.getRecords())){
            // 获取所有企业名称
            Map<Integer, String> qyMap = userService.getQyMap();
            // 获取所有职位名称
            Map<Integer, String> recruitmentMap = recruitmentService.getRecruitmentMap();
            result.getRecords().forEach(item->{
                item.setQyName(qyMap.get(item.getQyId()));
                item.setRecName(recruitmentMap.get(item.getRecruitId()));
            });
        }
        return CommonResult.success(result);
    }
    // 列表查询（不分页）
    @GetMapping("/notesList")
    public CommonResult notesList() {
        //查询用户已经面试通过的职位信息，可以写面试日志或工作日志
        LambdaQueryWrapper<NotesManage> queryWrapper = new LambdaQueryWrapper<NotesManage>()
                .eq(NotesManage::getUid, UserContext.getUserId())
                .eq(NotesManage::getOfferStatus, OfferStatus.MSTG.getCode());
        // 获取所有职位投递名称
        List<NotesManage> list = notesManageService.list(queryWrapper);
        List<NotesAndRecVo> notesAndRecVoList = Collections.emptyList();
        if(CollectionUtil.isNotEmpty(list)){
            // 获取所有职位类型
            Map<Integer, String> recruitmentMap = recruitmentService.getRecruitmentMap();
            notesAndRecVoList = list.stream()
                    .map(item -> {
                        NotesAndRecVo notesAndRecVo = new NotesAndRecVo();
                        notesAndRecVo.setValue(item.getNid());
                        notesAndRecVo.setLabel(recruitmentMap.get(item.getRecId()));
                        return notesAndRecVo;
                    })
                    .collect(Collectors.toList());
        }
        
        return CommonResult.success(notesAndRecVoList);
    }
}

